//
//  SWAuthEntranceViewController.swift
//  ChildStory
//
//  Created by linhan on 2016/12/13.
//  Copyright © 2016年 Aiya. All rights reserved.
//

import Foundation
import UIKit
class SWAuthEntranceViewController: SWBaseViewController,SWAPIComponent,WeixinHelperDelegate,ScrollADImageDelagate
{
    lazy private var _pageControl:UIPageControl = UIPageControl()
    private var _scrollADImage:ScrollADImage?
    
    override func viewDidLoad()
    {
        super.viewDidLoad()
        setup()
    }
    
    override func viewDidAppear(_ animated: Bool)
    {
        super.viewDidAppear(animated)
        
        WeixinHelper.shared().authViewController = self
        WeixinHelper.shared().delegate = self
    }
    
    override var prefersStatusBarHidden:Bool
    {
        return true
    }
    
    //MARK ============================================================================================
    //==============================            Private Method          ===============================
    //=================================================================================================
    
    
    private func setup()
    {
        view.backgroundColor = UIColor.white
        
        let bottomViewHeight:CGFloat = 160.0
        
        var images:[UIImage?] = [UIImage(named:"auth_img_introduction1.jpg"),
                                 UIImage(named:"auth_img_introduction2.jpg")]
        images = images.flatMap({$0})
        
        let introductionView:UIView = UIView()
        introductionView.frame = CGRectMake(0, 0, view.width, view.height - bottomViewHeight)
        view.addSubview(introductionView)
        
        let scrollADImage = ScrollADImage(frame: introductionView.bounds)
        scrollADImage.delegate = self
        scrollADImage.autoScrollInterval = 6
        scrollADImage.backgroundColor = UIColor.white
        scrollADImage.images = images
        introductionView.addSubview(scrollADImage)
        _scrollADImage = scrollADImage
        
        _pageControl.backgroundColor = UIColor.clear
        _pageControl.currentPageIndicatorTintColor = UIColor(hex: 0xffaabc)
        _pageControl.isUserInteractionEnabled = false
        _pageControl.currentPage = 0
        _pageControl.numberOfPages = images.count
        _pageControl.sizeToFit()
        _pageControl.center = CGPointMake(introductionView.width * 0.5, introductionView.height - 25)
        introductionView.addSubview(_pageControl)
        
        
    }
    
    private func createBottomView()
    {
        let bottomViewHeight:CGFloat = 160.0
        
        //登陆按钮
        let buttonTopMargin:CGFloat = 15
        let buttonLeftMargin:CGFloat = 15
        let buttonRightMargin:CGFloat = 15
        let buttonGrid:CGFloat = 15
        
        let bottomView:UIView = UIView()
        bottomView.backgroundColor = UIColor.white
        bottomView.frame = CGRectMake(0, view.height - bottomViewHeight, view.width, bottomViewHeight)
        view.addSubview(bottomView)
        
        let wechatBtnWidth:CGFloat = (view.width - buttonGrid - buttonLeftMargin - buttonRightMargin) / 2
        let wechatBtn:UIButton = UIButton(type: .system)
        wechatBtn.setTitle("微信", for: .normal)
        wechatBtn.setTitleColor(UIColor.white, for: .normal)
        wechatBtn.titleLabel?.font = UIFont.systemFont(ofSize: 18)
        wechatBtn.layer.cornerRadius = 1
        wechatBtn.layer.masksToBounds = true
        wechatBtn.backgroundColor = UIColor(hex: 0x00bf0a)
        wechatBtn.addTarget(self, action: #selector(wechatBtnTapped), for: .touchUpInside)
        wechatBtn.frame = CGRectMake(buttonLeftMargin, buttonTopMargin, wechatBtnWidth, 50)
        bottomView.addSubview(wechatBtn)
        
        let loginBtn:UIButton = UIButton(type: .system)
        loginBtn.setTitle("登录", for: .normal)
        loginBtn.setTitleColor(UIColor.white, for: .normal)
        loginBtn.titleLabel?.font = UIFont.systemFont(ofSize: 18)
        loginBtn.layer.cornerRadius = 1
        loginBtn.layer.masksToBounds = true
        loginBtn.backgroundColor = UIColor(hex: 0xf46363)
        loginBtn.addTarget(self, action: #selector(loginBtnTapped), for: .touchUpInside)
        loginBtn.frame = CGRectMake(wechatBtn.right + buttonGrid, buttonTopMargin, wechatBtnWidth, 50)
        bottomView.addSubview(loginBtn)
        
        let regBtnWidth:CGFloat = view.width - buttonLeftMargin - buttonRightMargin
        let regBtn:UIButton = UIButton(type: .system)
        regBtn.setTitle("注册", for: .normal)
        regBtn.setTitleColor(UIColor.white, for: .normal)
        regBtn.titleLabel?.font = UIFont.systemFont(ofSize: 18)
        regBtn.layer.cornerRadius = 1
        regBtn.layer.masksToBounds = true
        regBtn.backgroundColor = UIColor(hex: 0x84d3ed)
        regBtn.addTarget(self, action: #selector(regBtnTapped), for: .touchUpInside)
        regBtn.frame = CGRectMake(buttonLeftMargin, wechatBtn.bottom + buttonGrid, regBtnWidth, 50)
        bottomView.addSubview(regBtn)
    }
    
    private func loginFail(_ error:NSError)
    {
        SVProgressHUD.showError(withStatus:"登录失败，稍后重试")
    }
    
    //第三方平台登陆返回
    private func SSOLogin(_ connectionAccount:SWConnectionAccount, platform:ConnectionPlatform)
    {
        let account:SWMainAccount = SWMainAccount(connectionAccount: connectionAccount)
        SWAccountManager.sharedManager().logined(account:account)
        SVProgressHUD.showSuccess(withStatus:"登陆成功")
        SWMainApplication.sharedApplication.rootViewController?.showMainContent()
    }
    
    func weixinSignInSuccess(openID:String, userInfo:Wechat.User?)
    {
        if let userInfo = userInfo , openID != ""
        {
            let account:SWConnectionAccount = SWConnectionAccount(user: userInfo)
            SSOLogin(account, platform:.Wechat)
        }
        else
        {
            loginFail(SWError.DefaultNetworkError)
        }
    }
    
    //微信登陆失败
    func weixinSignInFail(code:Wechat.ErrorCode)
    {
        if code == Wechat.ErrorCode.Cancel || code == Wechat.ErrorCode.Denied
        {
            SVProgressHUD.showError(withStatus:"您已经取消或拒绝登录")
        }
        else
        {
            loginFail(SWError.DefaultNetworkError)
        }
    }
    
    func scrollADImage(_ scrollADImage: ScrollADImage, didScrollToIndex index: Int)
    {
        _pageControl.currentPage = index
    }
    
    @objc private func wechatBtnTapped()
    {
        WeixinHelper.shared().auth()
        if WeixinHelper.wechatAppInstalled
        {
            SVProgressHUD.show(withStatus:"登录中...")
        }
    }
    
    @objc private func loginBtnTapped()
    {
        navigationController?.pushViewController(SWLoginViewController(), animated: true)
    }
    
    @objc private func regBtnTapped()
    {
        navigationController?.pushViewController(SWRegisterViewController(), animated: true)
    }
    
    
    
}
